package log;
import java.io.*;
import java.util.*;
import java.text.DateFormat;
import java.text.SimpleDateFormat;


public class Log {
private static ArrayList<String> logList = new ArrayList<String>();


public enum priority {
		Warning("Ostrzeżenie"), Error("Błąd"), Message("Wiadomość");
		 
		 private String name;
		 
		 priority(String c) 
		 {
			 this.name = c;
		 }
		 
		 public String getName() 
		 {
			return name;
	     } 
};
	

public static <T> void console(T log, priority p)
{	
	System.out.println("[" + getDate() + "][Type: " + p.getName() + "][Message:" + log + "]");
	string(log,p);
}

public static <T> void console(T log)
{	
	System.out.println("[" + getDate() + "][Type: " + priority.Message.getName() + "][Message:" + log + "]");
	logList.add( string(log,priority.Message) );
}

public static <T> String string(T log, priority p)
{
	logList.add("[" + getDate() + "][Type: " + p.getName() + "][Message:" + log + "]\n");
	return "[" + getDate() + "][Type: " + p.getName() + "][Message:" + log + "]\n";
}


// Use LogString() or getDate() before SaveLog()
public static void saveLog()
{
	
		try{
		  // Create file 
		
		File mylog = new File("log.txt");
		FileOutputStream logStream = new FileOutputStream(mylog, false); // true to append
		                                                                 // false to overwrite.
		byte[] myBytes = new byte[10000];
		String logInSingleString = new String();
		for(String partOfLog : logList)
			logInSingleString += partOfLog;
		myBytes = logInSingleString.getBytes();
		logStream.write(myBytes);
		logStream.close();

		  }
	catch (Exception e){//Catch exception if any
		  System.err.println("Error: " + e.getMessage());
		  }
	
}

public static String readLog()
{
	
	ArrayList<String> result = new ArrayList<String>();
	String a = null;

    File aFile = new File("log.txt");

    if (!aFile.isFile())
    {
        //throw new IOException( fileName + " is not a regular File" );
        return a; // None
    }

    BufferedReader reader = null;

    try
    {
        reader = new BufferedReader(new FileReader(aFile));
    }
    catch (FileNotFoundException e1)
    {
        // TODO handle Exception
        e1.printStackTrace();

        return a;
    }

    String aLine = null;
   

    try {
		while ((aLine = reader.readLine()) != null)
		{
		    
			result.add(aLine + "\n");
		    
		}
		reader.close();
	} catch (IOException e) {
		e.printStackTrace();
	}

for(String e : result)
{
	if(a == null) a = e;
	else a = a + e;
}
return a;

	
}


public static String getDate()
{
	DateFormat dateFormat = new SimpleDateFormat("dd/MM/yyyy HH:mm:ss");
    Date date = new Date();
    return dateFormat.format(date);

}
}

